
import 'package:bloctest/utils/http/HttpMethod.dart';
import 'package:bloctest/utils/http/interceptor/DioInterceptor.dart';
import 'package:bloctest/utils/http/interceptor/ResInterceptor.dart';
import 'package:dio/dio.dart';

import 'ApiException.dart';

class DioInstance {
  static DioInstance? _instance;

  DioInstance._();

  final Dio _dio = Dio();
  final Duration _time = const Duration(seconds: 30);

  static DioInstance instance() {
    return _instance ??= DioInstance._();
  }

  void initDio(baseUrl) {
    _dio.options = BaseOptions(
        method: 'GET',
        baseUrl: baseUrl,
        connectTimeout: _time,
        receiveTimeout: _time,
        sendTimeout: _time);
    _dio.interceptors.add(DioInterceptor());
    _dio.interceptors.add(ResInterceptor());
  }

  Future request(url, method,
      {Map<String, dynamic>? queryParameters, data}) async {
    try {
      _dio.options.method = method;
      return await _dio.request(url,
          data: data, queryParameters: queryParameters);
    } catch (e) {
      // // 4. 捕获异常，处理错误
      throw ApiException(message: 'Error: ${e}', code: 0);
    } finally {
      // 5. 隐藏加载动画
    }
  }

  Future doGet(url, params) async {
    return await request(url, HttpMethod.GET,
        queryParameters: params, data: {});
  }

  Future doPost(url, {params, data}) async {
    return await request(url, HttpMethod.POST,
        queryParameters: params, data: data);
  }
}
